#include "mqtt.h"


StaticJsonDocument<200> json_doc,json_rep;//json对象

long lastReconnectAttempt = 0;

boolean reconnect() {
Serial.println("mqtt connceting server.");
if (mqtt_client.connect(host_name,account,passwd)) {
    Serial.println("mqtt connceted server.");
    mqtt_client.subscribe(mqtt_sub_topic,1);
// Once connected, publish an announcement...
// mqtt_client.publish("outTopic","hello world");
// ... and resubscribe
// mqtt_client.subscribe("inTopic");
}
return mqtt_client.connected();
}

void callback(char* topic, byte* payload, unsigned int length) {
    Serial.print("Message arrived [");
    Serial.print(topic);   // 打印主题信息
    Serial.print("] ");
    for (int i = 0; i < length; i++) 
    {
        Serial.print((char)payload[i]); // 打印主题内容
    }
    Serial.println();
    DeserializationError error = deserializeJson(json_doc,payload); 

    if(!error)
    {
        if(!((String)topic).compareTo(mqtt_sub_topic))
            {
            if(json_doc["ac"]=="open1")
            {
                if(work_state==0){
                    work_state=json_doc["io"];
                    if(work_state==9){
                        mqtt_jzz=json_doc["jzz1"];
                    }
                    else if(work_state==11){
                        mqtt_jzz=json_doc["jzz2"];
                    }
                    else if(work_state==18){
                        natie_time=json_doc["nt_time"];
                    }
                    else if(work_state==19){
                        kabuqinuo_time=json_doc["kb_time"];
                    }
                    else if(work_state==20){
                        yishi_time=json_doc["yi_time"];
                    }
                    else if(work_state==21){
                        clean_time=json_doc["wash_time"];
                    }
                    else if(work_state==22){
                        yeru_pluse=json_doc["ye_num"];
                    }
                    else if(work_state==23){
                        work_times=json_doc["sum_num"];
                        // Serial.printf("sum_num %d\n",work_times);
                    }
                    else if(work_state==25){
                        json_rep.clear();
                        json_rep["io"]="25";
                        json_rep["num"]=work_times;
                        char state_doc[measureJson(json_rep) + 1];
                        serializeJson(json_rep, state_doc, measureJson(json_rep) + 1);
                        mqtt_client.publish(mqtt_pub_topic,state_doc);
                        // work_times=json_doc["sum_num"];
                        // Serial.printf("sum_num %d\n",work_times);
                    }
                    json_rep.clear();
                    json_rep["state"]="ok";
                    json_rep["io"]=work_state;
                    char state_doc[measureJson(json_rep) + 1];
                    serializeJson(json_rep, state_doc, measureJson(json_rep) + 1);
                    mqtt_client.publish(mqtt_pub_topic,state_doc);
                }
                else{
                    Serial.printf("busy.....\n");
                    json_rep.clear();
                    json_rep["state"]="busy";
                    json_rep["io"]=work_state;
                    char state_doc[measureJson(json_rep) + 1];
                    serializeJson(json_rep, state_doc, measureJson(json_rep) + 1);
                    mqtt_client.publish(mqtt_pub_topic,state_doc);
                }
            }
            }
    }
}

void mqtt_loop(void *pvParameters)
{
while(1)
{
if (!mqtt_client.connected()) {
WIFI_connect();                                                    //函数会判断wifi是否连接，若是wifi断开会执行到wifi重连再返回，否则直接返回
long now = millis();
if (now - lastReconnectAttempt > 5000) {
    lastReconnectAttempt = now;
    // Attempt to reconnect
    if (reconnect()) {
    lastReconnectAttempt = 0;
    }
}
} else {
// Client connected
//上电第一次连上mqtt发送当前工作次数
if(pub_state==0){
    json_rep.clear();
    json_rep["type"]="num";
    json_rep["value"]=work_times;
    char state_doc[measureJson(json_rep) + 1];
    serializeJson(json_rep, state_doc, measureJson(json_rep) + 1);
    mqtt_client.publish(mqtt_pub_topic,state_doc);
    pub_state=1;
}
mqtt_client.loop();
}

delay(1000);
}
}

void mqtt_init(void)
{
    strcpy(account,mac);
    sprintf(mqtt_sub_topic,"/c/%s/get",mac);
    sprintf(mqtt_pub_topic,"/c/%s/send",mac);
    mqtt_client.setClient(wifi_client);
    mqtt_client.setServer(mqtt_server, mqtt_port);                              //设定MQTT服务器与使用的端口，1883是默认的MQTT端口
    mqtt_client.setCallback(callback);                                          //设定回调方式，当ESP8266收到订阅消息时会调用此方法

}